package com.rt.code.utils.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class WebUtils {

	public static boolean isLoginSuccess(HttpSession session){
		if(session.getAttribute("_userId") == null) return false;
		String userId = String.valueOf(session.getAttribute("userId"));
		if(Integer.parseInt(userId)<=0){
			return false;
		}
		return true;
	}
	/**
	 * 取session中存储的用户名
	 * @return
	 */
	public static String getUsername(HttpServletRequest request){
		String adminMan = (String)request.getSession().getAttribute("username");
		return adminMan;
	}
	/**
	 * 取session中存储的用户名ID
	 * @return
	 */
	public static Long getUserId(HttpServletRequest request){
		Long userId = (Long)request.getSession().getAttribute("userId");
		if(userId == null){
			return null;
		}
		return userId;
	}
	/**
	 * 取session中存储的登录用户所属公司
	 * @return
	 */
	public static Long getCompanyId(HttpServletRequest request){
		Long companyId = (Long)request.getSession().getAttribute("companyId");
		if(companyId == null){
			return null;
		}
		return companyId;
	}



	public static String getRealIp(HttpServletRequest request){
		return getRemortIP(request);
	}
	
	public static String getPath(HttpServletRequest request){
		String path = request.getContextPath();
		return path;
	}
	
	public static String getBasePath(HttpServletRequest request){
		String path = WebUtils.getPath(request);
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		return basePath;
	}
	
	
	public static String getRemortIP(HttpServletRequest request) 
    {
		String address = request.getHeader("x-forwarded-for");
		if (address == null)
		{
			return request.getRemoteAddr();
		}
		return WebUtils.getIpAddr(request);
	}
	
	private static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	

	public static void response1(String s, HttpServletResponse response){
		try {
			s = java.net.URLEncoder.encode(s, "GBK");
			PrintWriter out;
			out = response.getWriter();
			out.write(s);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void response(String s, HttpServletResponse response){
		try {
			response.setCharacterEncoding("GBK");
			PrintWriter out;
			out = response.getWriter();
			out.write(s);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
